#include "ros/ros.h"
#include "std_msgs/String.h"
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <sstream>
#include <alibabacloud/oss/OssClient.h>

using namespace AlibabaCloud::OSS;
using namespace std;
int uploadimg(string a);
string url;
std_msgs::String result;
ros::Publisher read_pub;
unsigned int fileNum = 1;
bool imageSaveFlag;
char key;
std_msgs::String result1; //
void imgCallback(const std_msgs::String::ConstPtr &msg) {
        ROS_INFO_STREAM("I heard: " << msg->data);
	key = 0;
        /*if (key != 1)
        {
		key =32;
	}
	else
	{
		key = 1;
	}*/
	if (msg->data == "p") // 5
        {
            key = 32;
        } else {
            key = 0;
        }
}
void imageTransCallback(const sensor_msgs::ImageConstPtr &msg) {
        try {
                        cv::imshow("show Image", cv_bridge::toCvShare(msg, "bgr8")->image);
                        cv::waitKey(30);
                        if (key == 32)
                        	imageSaveFlag = true;
                        key = 0;
			//key = 1;   //
                        if (imageSaveFlag) {
			imageSaveFlag = false; //
                        stringstream filePath;
                        filePath << "/home/liang/photo/" << fileNum << ".jpg"; ////
                        string fp = filePath.str(); //
                        cv::imwrite(fp, cv_bridge::toCvShare(msg, "bgr8")->image);
                        imageSaveFlag = false;
                        cout << fileNum << "had saved." << endl;
                        
                        int a = uploadimg(fp);
                        if(a == -1){
                                        cout<<"fail!!"<<endl;
                                        result.data = "-1";
                                        read_pub.publish(result);
                                        return;
                        }      
                        
                        result.data = url;
                        read_pub.publish(result);
                        cout << fileNum << "has been uploaded." << endl;
                        fileNum++;     ////
            }
        } catch (cv_bridge::Exception &e) {
                        ROS_ERROR("Could not convert from '%s' to 'bgr8'.", msg->encoding.c_str());
        }
}

int uploadimg(string a)
{
        /* 初始化OSS账号信息 */
        string AccessKeyId = "LTAI4FxrnjrBYKebVCGhqRgZ";
        string AccessKeySecret = " ";
        string Endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        string BucketName = "photo202001";
        /* yourObjectName表示上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg */
        /*string ObjectName = a; */
	//string ObjectName = "abc/123.jpg"; //不能以/开头
        
        stringstream filePath;
        filePath << "Photo" << "/" << fileNum << ".jpg";   ////
        string ObjectName = filePath.str();//不能以/开头
        //string GetobjectUrlName = "ROS";
        string GetobjectUrlName = filePath.str();  ////
        /* 初始化网络等资源 */
        InitializeSdk();

        ClientConfiguration conf;
        OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

        /* 上传文件 */
        /* yourLocalFilename由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt.*/

        auto outcome = client.PutObject(BucketName, ObjectName,a);   
        
        if (!outcome.isSuccess()) {
                        /* 异常处理 */
                        cout << "PutObject fail" <<
                        ",code:" << outcome.error().Code() <<
                        ",message:" << outcome.error().Message() <<
                        ",requestId:" << outcome.error().RequestId() <<endl;
                        ShutdownSdk();
                        return -1;
        }

        /* 设置签名URL有效时间*/
        time_t t = std::time(nullptr) + 1200;
        /* 生成下载文件URL */
        auto genOutcome = client.GeneratePresignedUrl(BucketName, GetobjectUrlName, t, Http::Get);
        if (genOutcome.isSuccess()) {
                        cout << "GeneratePresignedUrl success, Gen url:" << genOutcome.result().c_str() << endl;
                        url = genOutcome.result().c_str();
        }
        else {
                        /* 异常处理 */
                        cout << "GeneratePresignedUrl fail" <<
                        ",code:" << genOutcome.error().Code() <<
                        ",message:" << genOutcome.error().Message() <<
                        ",requestId:" << genOutcome.error().RequestId() << endl;
                        ShutdownSdk();
                        return -1;
        }

        /* 释放网络等资源 */
        ShutdownSdk();
        return 1;
}

int main(int argc, char **argv) {
        ros::init(argc, argv, "img_Listener");
        ros::NodeHandle nh;
        cv::namedWindow("show Image");
        image_transport::ImageTransport it(nh);

        read_pub = nh.advertise<std_msgs::String>("/write", 1000);
	//read_pub = nh.advertise<std_msgs::String>("/read", 1000);  //
        ros::Subscriber sub2 = nh.subscribe("/read", 1000, imgCallback);
        image_transport::Subscriber sub =it.subscribe("/camera/rgb/image_raw", 1, imageTransCallback);
	
	result1.data = 9; //
	read_pub.publish(result1);//
        ros::spin();
	
        cv::destroyWindow("view");
        return 0;
}
